package core

import (
	"encoding/json"
	"io"
	"net/http"
)

type Context struct {
	Writer  http.ResponseWriter
	Request *http.Request
	Params  map[string]string
	Gateway *Gateway
}

func NewContext(w http.ResponseWriter, r *http.Request, gw *Gateway) *Context {
	return &Context{
		Writer:  w,
		Request: r,
		Params:  make(map[string]string),
		Gateway: gw,
	}
}

func (c *Context) Method() string {
	return c.Request.Method
}

func (c *Context) Path() string {
	return c.Request.URL.Path
}

func (c *Context) JSON(code int, obj interface{}) {
	c.Writer.Header().Set("Content-Type", "application/json")
	c.Writer.WriteHeader(code)
	json.NewEncoder(c.Writer).Encode(obj)
}

func (c *Context) GetHeader(key string) string {
	return c.Request.Header.Get(key)
}

// 添加 Body() 方法
func (c *Context) Body() []byte {
	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		return nil
	}
	return body
}

// 添加 BodyString() 方法方便使用
func (c *Context) BodyString() string {
	return string(c.Body())
}
